package ngat.oss.simulation;

import java.util.*;

/** Classes which wish to provide timing signals should implement this interface.*/
public class BasicTimeSignalGenerator implements TimeSignalGenerator {

    /** The current timestamp.*/
    long time;

    /** Maps listeners to their time signal requests.*/
    protected SortedMap listeners;
    
    /** Create a BasicTimeSignalGenerator.*/
    public BasicTimeSignalGenerator(long time) {
	listeners = new TreeMap();
	this.time = time;
    }

    /** Implementors should register the listener for a signal at the speicified time.*/
    public void awaitTimingSignal(TimeSignalListener tsl, long time) {
	listeners.put(new Long(time), tsl);
    }

    /** Update the time, notify any awaiting listeners.*/
    public void updateTime(long updatedTime) {
	// update the current timestamp.

	//System.err.println("BTSG::update("+ScheduleSimulator.sdf.format(new Date(updatedTime))+")");
	
	time = updatedTime;

	if (listeners.isEmpty())
	    return;

	Long lt = (Long)listeners.firstKey();
	if (lt == null)
		return;
	long atime = lt.longValue();
	while (atime < updatedTime) {

	    TimeSignalListener tsl = (TimeSignalListener)listeners.get(lt);
	    listeners.remove(lt);

	    // Signal the listener with its requested time.
	    tsl.timingSignal(atime);
	   
	    if (listeners.isEmpty())
		return;
	    lt = (Long)listeners.firstKey();
	    if (lt == null)
		return;
	    
	    atime = lt.longValue();
	    
	}

    }

	public long getTime() {
		return time;
	}

}

